/*
Copyright (C) 2007 Kamal Singh.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var url = "http://feeds.feedburner.com/InterfaceliftNewestWallpaper?format=xml";
var results = new Array;
var previous;
var state = false;

function buttonDisplay() {
  if (state == false) {
    download.opacity = 255;
    next.opacity = 255;
    state = true;
  }
  else {
    download.opacity = 120;
    next.opacity = 120;
    state = false;
  }
}

function view_onOpen() {
  parse(url);
}

var wallpaperIndex = 0;

function buttonHandler() {
  if (wallpaperIndex == results.length)
    wallpaperIndex = 0;
  else
    wallpaperIndex = wallpaperIndex + 1;
  displayNext(wallpaperIndex);
}

function displayNext(wallpaperIndex) {
  var r = results[wallpaperIndex];
  previous = wallpaperIndex;
  title.innerText = r.title;
  author.innerText = "by  " + r.author;
  loadImage(r.image);
  wallpaper_image.tooltip = r.desc;
}

// Opens the requested URL using the user's default web browser
function openURL() {
  try {
    var r = results[previous];
    var url = r.link;
    var shell = new ActiveXObject("Shell.Application");
    shell.ShellExecute(url);
  } catch (e) {
    return;
  }
}

function displayContent() {
  var nItems = results.length;
  var random_wallpaper = Math.floor(Math.random() * nItems);
  previous = random_wallpaper;
  var r = results[random_wallpaper];
  title.innerText = r.title;
  author.innerText = "by  " + r.author;
  loadImage(r.image);
  wallpaper_image.tooltip = r.desc;
}

function loadImage(img) {
  
  try {
    var http = new XMLHttpRequest();
    http.open("GET", img, false);
    http.onreadystatechange = HTTPData;
    http.send(null);
  } 
  catch(err) {
    debug.error("can't get image");
    return;
  }

  function HTTPData() {
    if (http.readyState == 4) {
      try {
        wallpaper_image.src = http.responseStream;
      } 
      catch(e) {
        return;
      }
    }
  }
}

function parse(url) {
  var feedRequest = null;
  
  feedRequest = new XMLHttpRequest();
  try {
    feedRequest.open("GET", url, true);
    feedRequest.setRequestHeader("Cache-Control", "no-cache");
  } 
  catch (e) {
    // Catch invalid URLs
    feedRequest = null;
    return;
  }
  
  // Set the callback for when the downloading is completed (or failed)
  feedRequest.onreadystatechange = onFeedLoad;
  
  // Start the download
  try {
    feedRequest.send();
  }
  catch (e) {
    // Catch errors sending the request
    feedRequest = null;
    return;
  }
  
  function onFeedLoad() {
    // Verify that the download completed
    if (feedRequest.readyState != 4)
      return;

    // Verify that the download was successful
    if (feedRequest.status != 200) {
      feedRequest = null;
      return;
    }
    
    var doc = new DOMDocument();
    doc.loadXML(feedRequest.responseText);
    
    var elem = doc.getElementsByTagName("item");
    results = [];
    
    if (elem != null && elem.length > 0) {
      for (var z = 0; z < elem.length; z++) {
        var title, link, author, image, desc;
        for (var node = elem[z].firstChild; node != null; node = node.nextSibling) {
          if (node.nodeName == "title") {
            try {
              title = node.firstChild.nodeValue;
            }
            catch (e) {
              title = "";
            }  
          }
          if (node.nodeName == "link") {
            try {
              link = node.firstChild.nodeValue;
            }            	
            catch (e) {
              link = "";
            }
          }
          if (node.nodeName == "author") {
            try {
              author = node.firstChild.nodeValue;
            }            	
            catch (e) {
              author = "";
            }
          }
          if (node.nodeName == "description") {
            try {
              var tmpImage = node.firstChild.nodeValue;
			        tmpImage = tmpImage.substr(tmpImage.indexOf('<img'));
			        tmpImage = tmpImage.substr(0,tmpImage.indexOf('>'));
			        tmpImage = tmpImage.substr(tmpImage.indexOf('"')+1);
			        tmpImage = tmpImage.substr(0,tmpImage.indexOf('"'));
              image = tmpImage;

              var tmpDesc = node.firstChild.nodeValue;
			        tmpDesc = tmpDesc.substr(tmpDesc.indexOf('alt'));
			        tmpDesc = tmpDesc.substr(0,tmpDesc.indexOf('>'));
			        tmpDesc = tmpDesc.substr(tmpDesc.indexOf('"')+1);
			        tmpDesc = tmpDesc.substr(0,tmpDesc.indexOf('"'));
            }            	
            catch (e) {
              image = "";
              desc = "";
            }
          }
          results[z] = {title:title, author:author, link:link, image:image, desc:desc};
        }
      }
    }
    displayContent();
    view.setInterval(displayContent, 1000*60*5);  // every 5 mins show different wallpaper
    feedRequest = null;
  }
}